package br.macedo.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;

public class DAO<T> {
	private final EntityManager em;
	private final Class<T> classe;
	
	public DAO(EntityManager em, Class<T> classe)
	{
		this.em = em;
		this.classe = classe;
	}
	
	public void adiciona(T t)
	{
		this.em.persist(t);
	}
	
	public T altera(T t)
	{
		return this.em.merge(t);
	}
	
	public void remove(T t)
	{
		this.em.remove(t);
	}
	
	public T busca(Integer id) {
		if (id == null) return null;
		return em.find(classe, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> lista() {
		Session sessao = (Session) em.getDelegate();
		return sessao.createCriteria(classe).list();
		//  em.createQuery("from " + classe.getName()).getResultList();
	}
	
}
